<template>
  <div>
    <!--面包屑导航区域-->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!--卡片试图区域-->
    <el-card >
      <!--el-row  Layout 布局-->
      <el-row>
        <el-col>
          <el-button type="primary" @click="addRolesDialogVisible = true">添加角色</el-button>
        </el-col>
      </el-row>
      <!--表格视图区域-->
      <el-table :data="roles" border stripe style="font-size:12px">
        <!--展开列-->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row
              :class="['bdbottom',i1 === 0 ? 'bdtop':'']"
              v-for="(item1,i1) in scope.row.children"
              :key="item1.id"
            >
              <!--渲染一级权限-->
              <el-col :span="5">
                <el-tag closable @close="deleteRolel(scope.row,item1.id)">{{item1.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!--渲染二级权限和三级权限-->
              <el-col :span="19">
                <!--通过for循环嵌套二级权限-->
                <el-row
                  :class="[i2 ===0 ? '':'bdtop']"
                  v-for="(item2,i2) in item1.children"
                  :key="item2.id"
                >
                  <el-col :span="6">
                    <el-tag
                      closable
                      @close="deleteRolel(scope.row,item2.id)"
                      type="success"
                    >{{item2.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <!--通过for循环嵌套三级级权限-->
                    <el-tag
                      type="warning"
                      closable
                      @close="deleteRolel(scope.row,item3.id)"
                      v-for="item3 in item2.children"
                      :key="item3.id"
                    >{{item3.authName}}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <!--索引列-->
        <el-table-column type="index"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <!--操作显示列-->
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
              type="primary"
              size="mini"
              icon="el-icon-edit"
              @click="editRoles(scope.row.id)"
            >编辑</el-button>
            <el-button
              type="danger"
              size="mini"
              icon="el-icon-delete"
              @click="removeRolesByID(scope.row.id)"
            >删除</el-button>
            <el-button
              type="warning"
              size="mini"
              icon="el-icon-delete"
              @click="assignAuthority(scope.row)"
            >分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!--添加角色对话框-->
    <el-dialog title="添加角色" :visible.sync="addRolesDialogVisible" width="50%" @close="closeDialog">
      <!--添加角色表单-->
      <span>
        <el-form
          :model="addRolesForm"
          :rules="rolesFormRules"
          ref="addRolesForm"
          label-width="100px"
        >
          <el-form-item label="角色名称" prop="roleName">
            <el-input v-model="addRolesForm.roleName"></el-input>
          </el-form-item>
          <el-form-item label="角色描述">
            <el-input v-model="addRolesForm.roleDesc"></el-input>
          </el-form-item>
        </el-form>
      </span>
      <!--底部按钮区域-->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addRolesDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRoles">确 定</el-button>
      </span>
    </el-dialog>

    <!--修改角色对话框-->
    <el-dialog
      title="修改角色"
      :visible.sync="editRolesDialogVisible"
      width="50%"
      @close="editcloseDialog"
    >
      <!--修改角色表单-->
      <span>
        <el-form
          :model="editRolesForm"
          :rules="rolesFormRules"
          ref="editRolesForm"
          label-width="100px"
        >
          <el-form-item label="角色名称" prop="roleName">
            <el-input v-model="editRolesForm.roleName"></el-input>
          </el-form-item>
          <el-form-item label="角色描述">
            <el-input v-model="editRolesForm.roleDesc"></el-input>
          </el-form-item>
        </el-form>
      </span>
      <!--底部按钮区域-->
      <span slot="footer" class="dialog-footer">
        <el-button @click="editRolesDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="modifyingRoles">确 定</el-button>
      </span>
    </el-dialog>
    <!--分配权限对话框-->
    <el-dialog title="分配权限"  @close="setRightDialogClosed" :visible.sync="assignAuthorityDialogVisible" width="30%" >
      <span>
        <!--树形控件-->
        <el-tree
        :data="rolestree"
        :props="treeProps"
        show-checkbox
        node-key="id"
        default-expand-all
        :default-checked-keys="defkeys"
        ref="treeRef"
        >
        </el-tree>
      </span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="assignAuthorityDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRoles">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'roles',
  data () {
    return {
      // 所有角色列表
      roles: [],

      // 控制添加角色对话框的显示与隐藏
      addRolesDialogVisible: false,
      // 存放接受获取角色的信息
      addRolesForm: {
        roleName: '',
        roleDesc: ''
      },

      // 控制修改角色对话框的显示与隐藏
      editRolesDialogVisible: false,
      // 存放接受获取角色的信息
      editRolesForm: {},

      // 控制修改角色对话框的显示与隐藏
      assignAuthorityDialogVisible: false,
      // 所有的权限tree数据
      rolestree: [],
      // 树形控制要显示的内容
      treeProps: {
        children: 'children', // 嵌套的名称
        label: 'authName'// 要展示的字段名
      },
      // 接收存放默认选中的id值数组
      defkeys: [],
      // 当前即将分配权限的角色id
      rolesId: {},

      // 添加表单的校验规则
      rolesFormRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  created () {
    this.getRoleslist()
  },
  methods: {
    // 获取最新的角色列表
    async getRoleslist () {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        return this.$message.err('获取角色列表失败')
      }
      // console.log(res.data);
      this.roles = res.data
    },
    // 关闭（添加）对话框之前执行的事件
    closeDialog () {
      this.addRolesForm.roleDesc = ''
      this.$refs.addRolesForm.resetFields()
    },
    // 点击确定按钮-添加角色
    addRoles () {
      // 先验证表单是否符合规则
      this.$refs.addRolesForm.validate(async valid => {
        // 符合规则就发起请求
        if (!valid) return
        const { data: res } = await this.$http.post('roles', this.addRolesForm)
        // console.log(res)
        // 判断请求的结果是否等于成功的状态码
        if (res.meta.status !== 201) {
          return this.$message.error('添加角色失败')
        }
        this.getRoleslist()
        this.$message.success('添加用户成功')
        this.addRolesDialogVisible = false
      })
    },
    // 关闭（编辑）对话框之前执行的事件
    editcloseDialog () {
      this.editRolesForm.roleDesc = ''
      this.$refs.editRolesForm.resetFields()
    },
    // 点击编辑按钮-编辑角色
    async editRoles (id) {
      // console.log(id)
      const { data: res } = await this.$http.get('roles/' + id)
      // console.log(res)
      this.editRolesForm = res.data
      this.editRolesDialogVisible = true
    },
    // 点击确认按钮-确认修改角色
    modifyingRoles () {
      this.$refs.editRolesForm.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.put(
          'roles/' + this.editRolesForm.roleId,
          this.editRolesForm
        )
        // console.log(res)
        if (res.meta.status !== 200) {
          return this.$message.error('修改用户失败')
        }
        this.$message.success('修改用户成功')
        this.getRoleslist()
        this.editRolesDialogVisible = false
      })
    },
    // 点击删除按钮-根据id删除信息
    async removeRolesByID (id) {
      const confirmResult = await this.$confirm(
        '此操作将永久删除该角色, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)
      // console.log(confirmResult)
      // 如果用户确认删除，则返回值为字符串 confirm（确认）
      // 如果用户取消了删除，则返回值为字符串 cancel （取消）
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除')
      }
      // 单击了确认就发起删除请求
      const { data: res } = await this.$http.delete('roles/' + id, id)
      if (res.meta.status !== 200) {
        return this.$message.error('删除ID失败')
      }
      this.$message.success('删除成功')
      this.getRoleslist()
      // console.log(res)
    },
    // 展开列的确认删除权限
    async deleteRolel (role, rightId) {
      // console.log(id)
      const confirmResult = await this.$confirm(
        '此操作将永久删除该权限, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)
      // 如果用户确认删除，则返回值为字符串 confirm（确认）
      // 如果用户取消了删除，则返回值为字符串 cancel （取消）
      // console.log(confirmResult)
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除')
      }
      const { data: res } = await this.$http.delete(
        `roles/${role.id}/rights/${rightId}`
      )
      // console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error(删除权限失败)
      }
      // this.getRoleslist()
      role.children = res.data
      this.$message.success('删除成功')
    },
    // 展示分配权限的对话框
    async assignAuthority (role) {
      this.rolesId = role.id
      // 亲求获取所有权限的tree
      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) { return this.$message.error('获取权限列表失败') }
      // console.log(res)
      // console.log(role)
      this.rolestree = res.data
      // 递归获取三级节点的ID
      this.getLeafKeys(role, this.defkeys)
      this.assignAuthorityDialogVisible = true
    },
    // 通过递归的形式，获取角色下所有三级权限的id，并保存到defkeys数组中
    getLeafKeys (node, arr) {
      // 如果当前node节点不包含children属性，则是三级节点
      // console.log(node)
      if (!node.children) {
        return arr.push(node.id)
      }
      node.children.forEach(item =>
        this.getLeafKeys(item, arr))
      // console.log(node)
    },
    // 监听分配权限的对话框的关闭事件
    setRightDialogClosed () {
      this.defkeys = []
    },
    // 点击为角色分配权限
    async allotRoles () {
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      // console.log(keys)
      const idstr = keys.join(',')
      // console.log(idstr)
      const { data: res } = await this.$http.post(`roles/${this.rolesId}/rights`, { rids: idstr })
      // console.log(res)
      if (res.meta.status !== 200) { return this.$message.error('分配权限失败') }
      this.$message.success('分配权限成功')
      this.getRoleslist()
      this.assignAuthorityDialogVisible = false
    }
  }
}
</script>

<style lang="less" scoped>
//标签样式
.el-tag {
  margin-block: 7px;
  margin-left: 7px;
  margin-bottom: 7px;
}
.el-row {
  display: flex;
  align-items: center;
}
.bdtop {
  border-top: 1px solid #eee;
}
.bdbottom {
  border-bottom: 1px solid #eee;
}
</style>
